package server;

import java.net.*;
import java.io.*;

import client.data.KeyPairPair;

import encription.SecurityHandler;

/**
 * A server , which listens to a port and waits for clients
 * when a client connects ,  it creates a {@link MultiServerThread} which handles the client 
 */
public class MultiServer extends Thread{
	/**
	 * port which the server listens to
	 */
	private static final int DEFAULT_PORT = 1461;

	/**
	 * starts the server
	 */
	public void run(){
		try{
			KeyPairPair serverkeys = (KeyPairPair)SecurityHandler.readFromFile("./serverfile"); //get server private and public keys

			ServerSocket serverSocket = null;
			boolean listening = true; 
			//TODO read from file and write to file on exit (shared stuff)
			SharedStuff stuff = new SharedStuff(); //initialize the server database

			try {
				serverSocket = new ServerSocket(DEFAULT_PORT);		//starts listening
				System.out.println("Server: Ready ...");
			} catch (IOException e) {
				System.err.println("Could not listen on port: "+DEFAULT_PORT+".");
				System.exit(-1);
			}
			try{
				while (listening){		//wait for clients
					new MultiServerThread(serverSocket.accept(), stuff, serverkeys).start();
				}
				serverSocket.close();
			}catch(Exception e){
				SecurityHandler.catchException("waiting for clients", e, false);
				//e.printStackTrace();
			}
		} catch (Exception e1) {
			SecurityHandler.catchException("reading server private keys when initializing server", e1, false);
			//e1.printStackTrace();
		}
	}
	
	/**
	 * starts the server
	 * @param args
	 */
	public static void main(String[] args){
		new MultiServer().start();
	}
}
